import { useRef } from 'react';

import { articleApi, ArticleCard, ArticleCardLoader } from '@/entities/article';
import { productApi } from '@/entities/course';
import { transformArrayIntoObject } from '@/shared/lib';
import { Container, Grid, Title, Wrapper } from '@/shared/ui';
import { Filters, useFilters, useIsInputInFocus } from '@/widgets/Filters';
import { Footer } from '@/widgets/Footer';
import { Header } from '@/widgets/Header';
import cn from 'classnames';
import { useRouter } from 'next/router';
import { useDebounceValue } from 'usehooks-ts';

import cs from './Articles.module.scss';
import { NothingFound } from './ui/NothingFound';

export const Articles = () => {
  const router = useRouter();
  const [search] = useDebounceValue((router.query.search as string) || '', 300);

  const inputRef = useRef<HTMLInputElement>(null);
  const isInputInFocusProps = useIsInputInFocus({ inputRef });
  const isInputMode = isInputInFocusProps.isInputInFocus || search;

  const filterProps = useFilters();
  const { selectedPool } = filterProps;

  const { data: topics } = productApi.useGetTopicsQuery();
  const { data: formats } = articleApi.useGetArticleFormatsQuery();

  const selectedFormats = selectedPool.filter((v) => v.arr === 'formats');
  const selectedTopics = selectedPool.filter((v) => v.arr === 'topics');

  const searchQuery = { search };
  const filterQuery = {
    'filters[formats]': selectedFormats?.length ? selectedFormats.map((v) => v.id).toString() : undefined,
    'filters[topics]': selectedTopics?.length ? selectedTopics.map((v) => v.id).toString() : undefined,
  };

  const query = isInputMode ? searchQuery : filterQuery;

  const { data: articles, isLoading: isFetching } = articleApi.useGetArticlesQuery({
    ...query,
    'orderBy[publishedAt]': 'DESC',
    limit: 100,
  });
  return (
    <>
      <Header className={cn(isInputMode && 'hidden_mobile')} />
      <Wrapper>
        <Container>
          <Title className={cn(cs.title, isInputMode && 'hidden_mobile')}>Статьи</Title>
          <Filters
            {...isInputInFocusProps}
            {...filterProps}
            formats={formats?.formats.map((v) => v)}
            inputRef={inputRef}
            isInputMode={!!isInputMode}
            searchClassName={cs.input_container}
            topics={topics?.topics}
          />
          {!isFetching && !!articles?.articles?.length && (
            <Grid size="article">
              {articles?.articles?.map(({ image, id, publishedAt, title, superOrder }) => (
                <ArticleCard
                  date={publishedAt}
                  id={id}
                  image={image}
                  isAdvertising={!!superOrder}
                  key={id}
                  title={title}
                />
              ))}
            </Grid>
          )}
          {isFetching && (
            <Grid size="article">
              {transformArrayIntoObject(Array(10).fill(1)).map(({ id }) => (
                <ArticleCardLoader key={id} />
              ))}
            </Grid>
          )}
          {articles?.articles?.length === 0 && <NothingFound />}
        </Container>
      </Wrapper>
      <Footer className={cs.footer} />
    </>
  );
};
